<?php
namespace app\admin\controller;
use app\admin\Controller;
use app\admin\model\Store as StoreModel;
use pidan\facade\Request;
use pidan\facade\Db;


class Store extends Controller
{
	protected function initialize()
	{
		$this->model=new StoreModel;
	}
	public function list(){
		$req=$this->request;
		$table=$this->model;
		//查询字段
		$data=$req->only(['mall_id','name','status'],'get','trim');
		foreach($data as $k=>$v){
			if($v==='')  unset($data[$k]);
		}
		//要显示的
		$filed=explode(',','id,user_id as email,mall_id as mall_name,gapday,name,url,img,status,createtime');

		$sort_by=input('request.sort_by','id','trim');
		$sort_order=input('request.sort_order','asc','trim');

		$page=input('request.page',1,'intval');
		$limit=input('request.limit',30,'intval');

		$list= $table->field($filed);

		$count=$list->count('id');
		$list=$list->page($page)->where($data)->order($sort_by, $sort_order)->limit($limit)->select()->toArray();
		$mall=Db::name('mall')->column('name','id');
		foreach($list as $k=>$v){
			$list[$k]['mall_name']=$mall[$v['mall_name']];
		}
		return $this->lists($list,$count);
	}
	public function edit(){
		$app=$this->app;
		$req=$this->request;

		$data=[];
		$data['id']=$req->post('id',0,'intval');
		$data['mall_id']=$req->post('mall_id',0,'intval');
		$data['name']=$req->post('name','','trim,strip_tags');
		$data['url']=$req->post('url','trim,strip_tags');
		$data['img']=$req->post('img','trim,strip_tags');
		$data['gapday']=$req->post('gapday',0,'intval');
		//检查
		$msg='';
		if( Db::name('store')->where('id',$data['id'])->count('id') == 0){
			$msg='店铺已经不存在';
		}
		elseif($data['mall_id']==0 || Db::name('mall')->where('id',$data['mall_id'])->count('id') == 0 ){
			$msg='平台不存在';
		}
		elseif(empty($data['name'])){
			$msg='请填写店铺名称';
		}
		elseif(empty($data['url'])){
			$msg='请填写店铺首页链接';
		}
		elseif(empty($data['img'])){
			$msg='请上传店铺截图';
		}
		elseif($data['gapday']<0){
			$msg='请填写正确的接单间隔天数';
		}
		if(!empty($msg)){
			return $this->code(1,$msg);
		}

		Db::startTrans();
		try {
			$row = StoreModel::find($data['id']);
			$row->save($data);
			$result=['code'=>0,'msg'=>'操作成功'];
			Db::commit();
		} catch (\Exception $e) {
			Db::rollback();
			$result=['code'=>2,'msg'=>$e->getMessage()];
		}
		return $this->result($result);
	}

}
